package groups

import (
	"github.com/beego/beego/v2/client/orm"
	"xpms/app/models"
	"xpms/cores"
	"xpms/cores/utils"
)

type GroupsUser struct {
	Id      int64 `orm:"pk;" json:"Id,string"`
	Groupid int64 `json:"Groupid,string"`
	Userid  int64 `json:"Userid,string"`
}

type GroupsUserName struct {
	Id         int64 `json:"Id,string"`
	Userid     int64 `json:"Userid,string"`
	Realname   string
	Groupid    int64 `json:"Groupid,string"`
	Departid   int64 `json:"Departid,string"`
	Departname string
}

func (this *GroupsUser) TableName() string {
	return models.TableName("groups_user")
}

func init() {
	orm.RegisterModel(new(GroupsUser))
}

func AddGroupsUser(upd GroupsUser) error {
	o := orm.NewOrm()
	user := new(GroupsUser)

	user.Id = upd.Id
	user.Groupid = upd.Groupid
	user.Userid = upd.Userid
	_, err := o.Insert(user)
	return err
}

//得到用户组
func GetGroupByUser(groupid, userid string) (GroupsUser, error) {
	var user GroupsUser
	var err error
	o := orm.NewOrm()
	err = o.QueryTable(models.TableName("groups_user")).Filter("userid", userid).Filter("groupid", groupid).One(&user)
	if err == orm.ErrNoRows {
		return user, nil
	}
	return user, err
}
func DeleteGroupsUsers(ids []string) error {
	o := orm.NewOrm()
	sql := `
	DELETE FROM pms_groups_user 
	WHERE `
	param := make([]interface{}, 0, 0)
	if !utils.IsEmpty(ids) {
		sql = sql + ` id in(`
		sql1, value := cores.SqlInParam(ids)
		sql = sql + sql1 + `)`
		param = append(param, value...)
	}
	_, err := o.Raw(sql, param).Exec()
	return err
}

func ListGroupsUserAndName(groupid int64) (num int64, err error, user []GroupsUserName) {
	var users []GroupsUserName
	o := orm.NewOrm()
	sql := `
	SELECT
	  upr.userid,
	  upr.realname,
	  gu.groupid,
	  gu.id,
	  pos.positionid,
	  pos.name as departname
	FROM pms_groups_user AS gu
	  LEFT JOIN pms_users_profile AS
	  upr
		ON upr.userid = gu.userid
	  LEFT JOIN pms_positions AS pos
		ON pos.positionid = upr.positionid
	WHERE 1=1 
`
	param := make([]interface{}, 0, 0)
	if !utils.IsEmpty(groupid) {
		sql = sql + ` and  gu.groupid  in(`
		sql1, value := cores.SqlInParam(groupid)
		sql = sql + sql1 + `)`
		param = append(param, value...)
	}
	nums, err := o.Raw(sql, param).QueryRows(&users)
	return nums, err, users
}

func ListGroupsUser(condArr map[string]interface{}) (ops []interface{}) {
	o := orm.NewOrm()
	var list orm.ParamsList
	o.QueryTable("pms_groups_user").Filter("groupid__in", condArr["group"]).Distinct().ValuesFlat(&list, "userid")
	return list
}

type GroupsId struct {
	Groupid int64
}

func ListGroupsByUser(condArr map[string]interface{}) (ops []GroupsId) {
	o := orm.NewOrm()
	var list []GroupsId
	sql := `
	SELECT
	  pp.groupid groupid
	FROM  pms_groups_user pp
	WHERE 1 = 1 `
	param := make([]interface{}, 0, 0)
	if !utils.IsEmpty(condArr["userid"]) {
		sql = sql + ` and  pp.userid in(`
		sql1, value := cores.SqlInParam(condArr["userid"])
		sql = sql + sql1 + `)`
		param = append(param, value...)
	}
	o.Raw(sql, param).QueryRows(&list)
	return list
}
